<?php
namespace Resmodel;

use Core\Exception\BusinessException;
use Logger;
use Zend\Db\Adapter\Adapter;
use Zend\Db\Sql\Expression;
use Zend\Db\Sql\Predicate\Like;
use Zend\Db\Sql\Predicate\Operator;
use Zend\Db\Sql\Select;
use Zend\Db\Sql\TableIdentifier;
use Zend\InputFilter\InputFilter;

class ArticleTable extends ResAbstractTable
{

    /**
     * @param $id
     * @return Article
     */
    public function getArticle($id){
       return $this->getById($id);
    }

    /**
     * @param $header
     * @return Article
     */
    public function getArticleByHeader($header)
    {
       return $this->getByColumn('header', $header)->current();
    }

    /**
     * @param $alias
     * @return Article
     */
    public function getArticleByAlias($alias)
    {
        return $this->getByColumn('alias', $alias)->current();
    }

    /**
     * @return InputFilter
     */
    public function getInputFilter()
    {
        $filter = new InputFilter();

        return $filter;
    }

    public function searchAllArticle($isPaging, $offset, $rowPerPage, $orderArr = array('name'), $searchOption){

    }

    public function searchArticle($isPaging, $offset, $rowPerPage , $orderArray ,$searchOption )
    {
        $result=array();
        $select = $this->getDbSqlSelect();

        if($searchOption['header']){
            $select->where(array('header like "%'.$searchOption['header'].'%"'));
        }

        if($isPaging){
            $select->offset($offset)->limit($rowPerPage);
        }

        if($orderArray){
            $select->order($orderArray);
        }

        if($searchOption["categoryId"] && $searchOption["categoryId"] !='ALL'){
            $categoryService = new Category();
            $allParent = $categoryService->getAllChildren($searchOption["categoryId"]);
            $tmp = ','.$searchOption["categoryId"];
            foreach ($allParent as $parent) {
                $tmp = $tmp.",".$parent->id;
            }
            $tmp = '('.substr($tmp,1).')';

            $select->join(array('aac' => "article_category"), "article.id = aac.article_id", array());
            $select->where("aac.category_id in ".$tmp)
                ->where('is_primary = ?', 1);
        }

        if($searchOption["subCategoryId"] && $searchOption["subCategoryId"] !='ALL'){
            $categoryService = new Category();
            $allParent = $categoryService->getAllChildren($searchOption["subCategoryId"]);
            $tmp = ','.$searchOption["subCategoryId"];
            foreach ($allParent as $parent) {
                $tmp = $tmp.",".$parent->id;
            }
            $tmp = '('.substr($tmp,1).')';

            $select->join(array('aac2' => "article_category"), "article.id = aac2.article_id", array());
            $select->where("aac2.category_id in ".$tmp)
                ->where('is_primary = ?', 0);
        }

        $select->join( array('ur'=> new TableIdentifier('user', 'cms')),
            'ur.id = article.created_by',
            array("user_name"=>"username"));

//        Logger::debug($select->getSqlString($this->tableGateway->adapter->getPlatform()));
        $allRow = $this->executeSelectForArray($select);
        $dbMaxOrder = $this->getMaxOrderNumber();
        foreach ($allRow as $anArticle) {
            $anArticle->downable = 1;
            $anArticle->upable = 1;
            if($anArticle->order_number == 1)
                $anArticle->downable = 0;

            if($anArticle->order_number == $dbMaxOrder)
                $anArticle->upable = 0;

            $anArticle->order_number = ($anArticle->order_number - $dbMaxOrder -1)*(-1);

        }


        $total = $this->getCount($select);

        $result["total"] = $total;
        $result["rows"] = $allRow;
        return $result;
    }

    /**
     * @return \Zend\Db\ResultSet\ResultSet
     */
    public function getAllActiveArticle(){
        return $this->getTableGateway()->select(array('active'=>1));
    }



    public function addArticle($paramArr){
        $dbMaxOrder = $this->getMaxOrderNumber();
        if(!$dbMaxOrder || $dbMaxOrder == 0)
            $dbMaxOrder = 1;
        else
            $dbMaxOrder++;

       $id = $this->insert(array( 'header'=>$paramArr['header'],
            'sumarize'=>$paramArr['sumarize'],'thumbnail'=>$paramArr['thumbnail'],
            'alias'=>$paramArr['alias'],'content'=>$paramArr['content'],
            'active'=>$paramArr['active'], 'order_number'=>$dbMaxOrder));

        $articleItem = $this->getArticle($id);
        $articleItem->detachAllCategory();

        $categoryArr = $paramArr['categories'];
        if($categoryArr){
            foreach ($categoryArr as $aCategoryId) {
                $articleItem->addCategory($aCategoryId);
            }
        }

        $categoryArr = $paramArr['subCategories'];
        if($categoryArr){
            foreach ($categoryArr as $aCategoryId) {
                $articleItem->addCategory($aCategoryId);
            }
        }

    }

    public function updateArticle($paramArr){
         $this->update(array( 'header'=>$paramArr['header'],
            'sumarize'=>$paramArr['sumarize'],'thumbnail'=>$paramArr['thumbnail'],
            'alias'=>$paramArr['alias'],'content'=>$paramArr['content'],
            'active'=>$paramArr['active'],), $paramArr['id']);
        $id = $paramArr['id'];
        $articleItem = $this->getArticle($id);
        $articleItem->detachAllCategory();

        $categoryArr = $paramArr['categories'];
        if($categoryArr){
            foreach ($categoryArr as $aCategoryId) {
                $articleItem->addCategory($aCategoryId);
            }
        }

        $categoryArr = $paramArr['subCategories'];
        if($categoryArr){
            foreach ($categoryArr as $aCategoryId) {
                $articleItem->addCategory($aCategoryId);
            }
        }
    }


    public function toggleActiveOfArticle($id){
        $article = $this->getArticle($id);
        $active = $article->active == 1?0:1;
        $this->update(array('active'=>$active), $id);
    }

    public function doDelete($id){
        $article = $this->getArticle($id);
        $article->detachAllCategory();
        $this->delete($id);

        $this->getTableGateway()->update(array('order_number'=>new Expression('order_number - 1')),
            array('order_number > '.$article->order_number));
    }

    public function upArticle($id){
        $article = $this->getArticle($id);
        $brother = $this->getUpperBrother($article);
        $this->update(array('order_number'=>$brother->order_number - 1),$brother->id );
        $this->update(array('order_number'=>$article->order_number + 1),$article->id );
    }

    private function getUpperBrother($sampleArticle){
        $brotherOrder = $sampleArticle->order_number + 1;
        $brother = $this->getByColumn('order_number', $brotherOrder)->current();
        if(!$brother) throw new BusinessException('Không tìm được bài viết xếp trên');
        return $brother;
    }
    private function getLowerBrother($sampleArticle){
        $brotherOrder = $sampleArticle->order_number - 1;
        $brother = $this->getByColumn('order_number', $brotherOrder)->current();
        if(!$brother) throw new BusinessException('Không tìm được bài viết xếp trên');
        return $brother;
    }

    public function downArticle($id){
        $article = $this->getArticle($id);
        $brother = $this->getLowerBrother($article);
        $this->update(array('order_number'=>$brother->order_number + 1),$brother->id );
        $this->update(array('order_number'=>$article->order_number - 1),$article->id );
    }


}